<template>
  <canvas
    :canvas-id="canvasId"
    :style="{width: width + 'px', height: height + 'px', display: 'block', background: '#fff', borderRadius: '8rpx', boxShadow: '0 2rpx 8rpx #eee'}"
    @click="drawCaptcha"
  ></canvas>
</template>

<script>
export default {
  props: {
    width: { type: Number, default: 120 },
    height: { type: Number, default: 40 },
    length: { type: Number, default: 4 }
  },
  data() {
    return {
      code: '',
      canvasId: 'captcha-canvas-' + Math.random().toString(36).substr(2, 8)
    }
  },
  mounted() {
    this.drawCaptcha();
  },
  methods: {
    randomColor(min, max) {
      const r = min + Math.floor(Math.random() * (max - min));
      const g = min + Math.floor(Math.random() * (max - min));
      const b = min + Math.floor(Math.random() * (max - min));
      return `rgb(${r},${g},${b})`;
    },
    randomChar() {
      const chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
      return chars.charAt(Math.floor(Math.random() * chars.length));
    },
    drawCaptcha() {
      const ctx = uni.createCanvasContext(this.canvasId, this);
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, this.width, this.height);

      // 生成验证码
      let code = '';
      for (let i = 0; i < this.length; i++) {
        const char = this.randomChar();
        code += char;
        const fontSize = 22 + Math.random() * 8;
        const deg = (Math.random() - 0.5) * 0.6; // -0.3 ~ 0.3 弧度
        ctx.save();
        ctx.setFontSize(fontSize);
        ctx.setFillStyle(this.randomColor(50, 160));
        ctx.translate(20 + i * 22, 25);
        ctx.rotate(deg);
        ctx.fillText(char, 0, 0);
        ctx.restore();
      }
      this.code = code;

      // 干扰线
      for (let i = 0; i < 4; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * this.width, Math.random() * this.height);
        ctx.lineTo(Math.random() * this.width, Math.random() * this.height);
        ctx.setStrokeStyle(this.randomColor(100, 200));
        ctx.stroke();
      }
      // 干扰点
      for (let i = 0; i < 30; i++) {
        ctx.beginPath();
        const x = Math.random() * this.width;
        const y = Math.random() * this.height;
        ctx.arc(x, y, 1, 0, 2 * Math.PI);
        ctx.setFillStyle(this.randomColor(150, 255));
        ctx.fill();
      }
      
      // 修复异步绘制问题，确保emit的验证码与用户看到的验证码一致
      if (typeof ctx.draw === 'function' && ctx.draw.length > 0) {
        // 支持 draw 回调的端（小程序/APP）
        ctx.draw(false, () => {
          this.$emit('update', code);
        });
      } else {
        // H5 端，使用 setTimeout 延迟 emit
        ctx.draw();
        setTimeout(() => {
          this.$emit('update', code);
        }, 50);
      }
    }
  }
}
</script>